let login = getCookie("login");
if (!login) {
  localStorage.setItem("url", location.href);
  location.href = "../html/login.html";
}

let array = [];

let p = pAjax({
  url: "/sa/getCarData.php",
  type: "post",
  data: {
    user: login,
  },
});
p.then((res) => {
  res = JSON.parse(res); //数据库
  
  let re = localStorage.getItem("data"); //本地存储
  // console.log(re);
  re = JSON.parse(re);
  re = re.data;
  // console.log(re);
  re.forEach((items) => {
    res.forEach((ite) => {
      if (items.id == ite.goods_id) {
        let obj = Object.assign(items, ite);
        array.push(obj);
      }
    });
  });
  render(array);
  calculation()
});

//渲染数据
function render(da) {
  let pinlei = document.querySelector(".pinlei");
  if(!da ||da.length==0){
    return pinlei.innerHTML= `<img class="tutu" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fa4064bdab5f6c800ed664014f3eb7d13a4dd25b3138d0-hYHe07_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1635478991&t=ce7de306ee628053e57586f0e1f0a180" alt="">`
  }
  pinlei.innerHTML = da
    .map((item, index) => {
      return ` <div class="pin" idx=${item.id}>
    <div class="lef">
      <div class="goutu">
        ${ig(item)}
      </div>
    </div>
    <div class="rig">
      <div class="rig1">
        <h4 class="taozhi">${item.name}</h4>
        <div class="jiaqian">
          <span class="jian">￥${item.prices} / 件</span>
          <p index=${index}>
            <button id="jianfa" ${item.goods_num==1?"disabled":""}>-</button>
            <span class="num">${item.goods_num}</span>
            <button id="jiafa">+</button>
          </p>
          <span class="numjia">￥${(item.prices*item.goods_num).toFixed(2)}</span>
        </div>
      </div>
      ${pan(item)}
      <button class="del">删除</button>
    </div>
  </div>`;
    })
    .join("");
}
function ig(data){
  if(data.img){
    return `<img src="${data.im}" alt="" />`
  }else{
    return `<img src="${data.ims}" alt="" />`
  }
}
function pan(data){
  if(data.ke){
    return ` <div class="right2">${data.ke}克</div>`
  }else{
    return `<div class="right2">16厘米 | 适合${data.shihe}食用 | +${data.can}套餐具</div>`
  }
}
let pinlei = document.querySelector(".pinlei");
pinlei.onclick = (e) => {
  var e = e || window.event;
  if (e.target.classList.contains("del")) {
    let id = e.target.parentNode.parentNode.getAttribute("idx");
    // console.log(id);
    if (!confirm("确定删除这个商品吗")) 
      return;
      let p1 = pAjax({
        url: "/sa/removeCarData.php",
        data: {
          user: login,
          goods_id: id,
        },
      });
      p1.then((res) => {
        res = JSON.parse(res);
        if (res.code) {
          array = array.filter((item) => {
            return item.id != id;
          });
          console.log(array);
          calculation()
          render(array);
        }
      });
  }
  
//减少数量
  if(e.target.id=="jianfa"){
    let idx=e.target.parentNode.getAttribute("index");
    array[idx].goods_num-=1;
    updata(idx,array[idx].goods_num);
    calculation()
    render(array);

  }
  //增加数量
  if(e.target.id=="jiafa"){
    let idx=e.target.parentNode.getAttribute("index");
    array[idx].goods_num=array[idx].goods_num*1+1;;
    updata(idx,array[idx].goods_num);
    calculation()
    render(array);
  }
};

//清空
let qingkong=document.querySelector(".qingkong");
  qingkong.onclick=(e)=>{
    // console.log(1);
    var e=e||window.event;
    let id = e.target.parentNode.parentNode.getAttribute("idx");
    if (!confirm('确定删除全部商品吗？')) return;
    let p2=pAjax({
      url:"/sa/clearCarData.php",
      data:{
        user:login,
        goods_id: id,
      }
    })
    p2.then((res)=>{
      res=JSON.parse(res);
      if (res.code) {
      //   array = array.filter((item) => {
      //     return item.id != id;
      //   });
      
      array=[];
      }
      // console.log(array);
      calculation();
      // render(array);
      return pinlei.innerHTML= `<img class="tutu" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fa4064bdab5f6c800ed664014f3eb7d13a4dd25b3138d0-hYHe07_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1635478991&t=ce7de306ee628053e57586f0e1f0a180" alt="">`
    })
  }
//商品的数量和总价格
function  calculation(){
  var shangpin=document.querySelector(".shangpin");
  // console.log(array);
  shangpin.innerHTML=array.length+"件商品";
  let total=document.querySelector('.total');
  let t=array.reduce((pre,item)=>{
    return pre+item.goods_num*item.prices;
  },0)
    total.innerHTML='￥'+t.toFixed(2);
}

// 数据库更新
function updata(index,num){
  let p=pAjax({
    url:'/sa/updCarData.php',
    data:{
      user:login,
      goods_id:index,
      goods_num:num
    }
  })
  p.then(res=>{
    res=JSON.parse(res);
    if(!res.code) return ;
    array.forEach((item)=>{
      if(item.goods_id==index){
        item.goods_num=num;
      }
    })
    render(array);
  })
}